from rpa_framework.core.workflow import NodeRegistry, Workflow, NodeType
# 使用标准logging模块
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
import os
import json
import re
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import pyautogui
import pygetwindow as gw

from PyQt5.QtWidgets import QWidget


class WorkflowNode:
    """工作流节点类 - 用于工作流设计器中的节点表示"""
    
    def __init__(self, node_id, node_type, position=None, params=None, name=""):
        """初始化工作流节点
        
        Args:
            node_id: 节点唯一标识符
            node_type: 节点类型
            position: 节点在设计器中的位置 (x, y)
            params: 节点参数字典
            name: 节点名称
        """
        self.node_id = node_id
        self.node_type = node_type
        self.position = position or (0, 0)
        self.params = params or {}
        self.name = name or f"{node_type}节点"
        self.connections = []  # 存储连接的目标节点ID
    
    def add_connection(self, target_node_id):
        """添加节点连接
        
        Args:
            target_node_id: 目标节点ID
        """
        if target_node_id not in self.connections:
            self.connections.append(target_node_id)
    
    def remove_connection(self, target_node_id):
        """移除节点连接
        
        Args:
            target_node_id: 目标节点ID
        """
        if target_node_id in self.connections:
            self.connections.remove(target_node_id)
    
    def to_dict(self):
        """将节点信息转换为字典格式
        
        Returns:
            节点信息字典
        """
        return {
            "id": self.node_id,
            "type": self.node_type,
            "position": self.position,
            "params": self.params,
            "name": self.name,
            "connections": self.connections
        }
    
    @classmethod
    def from_dict(cls, node_dict):
        """从字典创建节点实例
        
        Args:
            node_dict: 节点信息字典
            
        Returns:
            WorkflowNode实例
        """
        return cls(
            node_id=node_dict["id"],
            node_type=node_dict["type"],
            position=node_dict.get("position", (0, 0)),
            params=node_dict.get("params", {}),
            name=node_dict.get("name", "")
        )

class WorkflowDesignerWidget(QWidget):
    def __init__(self):
        super().__init__()
    def _create_task_function(self, node_type, node_params, node_name, previous_results=None):
        # 替换变量引用
        resolved_params = {}
        for param_name, param_value in node_params.items():
            if isinstance(param_value, str):
                original_value = param_value
                for var_ref in re.findall(r'\{\{([^}]+)\}\}', original_value):
                    # 尝试从previous_results中获取变量值
                    value = self._get_value_from_path(previous_results, var_ref.strip())
                    if value is not None:
                        original_value = original_value.replace(f"{{{{{var_ref}}}}}", str(value))
                resolved_params[param_name] = original_value
            else:
                resolved_params[param_name] = param_value
        
        # 使用NodeRegistry获取对应的执行器
        executor = NodeRegistry.get_node_executor(node_type)
        if executor:
            # 使用执行器执行节点
            return executor.execute(node_params=resolved_params, 
                                  previous_results=previous_results or {},
                                  node_name=node_name)
        else:
            # 回退到原有逻辑
            if node_type == "start":
                logger.info("工作流开始执行")
                return {"status": "success", "message": "工作流开始", "data": {"start_time": time.time()}}
            
            elif node_type == "end":
                logger.info("工作流执行结束")
                return {"status": "success", "message": "工作流结束", "data": {"end_time": time.time()}}
            
            elif node_type == "file":
                # 文件操作节点 - 支持读写文件
                operation = resolved_params.get("operation", "read")
                file_path = resolved_params.get("file_path", "")
                content = resolved_params.get("content", "")
                
                try:
                    if operation == "read":
                        with open(file_path, 'r', encoding='utf-8') as f:
                            data = f.read()
                        logger.info(f"成功读取文件: {file_path}")
                        return {"status": "success", "message": "文件读取成功", "data": {"content": data}}
                    elif operation == "write":
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(content)
                        logger.info(f"成功写入文件: {file_path}")
                        return {"status": "success", "message": "文件写入成功"}
                    elif operation == "append":
                        with open(file_path, 'a', encoding='utf-8') as f:
                            f.write(content)
                        logger.info(f"成功追加文件: {file_path}")
                        return {"status": "success", "message": "文件追加成功"}
                    elif operation == "exists":
                        exists = os.path.exists(file_path)
                        logger.info(f"检查文件是否存在: {file_path} -> {exists}")
                        return {"status": "success", "message": "文件检查完成", "data": {"exists": exists}}
                    else:
                        logger.error(f"未知的文件操作: {operation}")
                        return {"status": "error", "message": f"未知的文件操作: {operation}"}
                except Exception as e:
                    logger.error(f"文件操作失败: {str(e)}")
                    return {"status": "error", "message": f"文件操作失败: {str(e)}"}
            
            elif node_type == "browser":
                # 浏览器操作节点 - 使用Selenium
                from selenium import webdriver
                from selenium.webdriver.chrome.service import Service
                from webdriver_manager.chrome import ChromeDriverManager
                
                operation = resolved_params.get("operation", "open")
                url = resolved_params.get("url", "https://www.google.com")
                element = resolved_params.get("element", "")
                text = resolved_params.get("text", "")
                
                try:
                    # 初始化WebDriver
                    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
                    
                    if operation == "open":
                        driver.get(url)
                        logger.info(f"成功打开URL: {url}")
                        return {"status": "success", "message": "浏览器打开成功", "data": {"url": url}}
                    
                    elif operation == "click":
                        driver.get(url)
                        driver.find_element_by_css_selector(element).click()
                        logger.info(f"成功点击元素: {element}")
                        return {"status": "success", "message": "点击元素成功"}
                    
                    elif operation == "input":
                        driver.get(url)
                        driver.find_element_by_css_selector(element).send_keys(text)
                        logger.info(f"成功输入文本到元素: {element}")
                        return {"status": "success", "message": "文本输入成功"}
                    
                    elif operation == "get_text":
                        driver.get(url)
                        element_text = driver.find_element_by_css_selector(element).text
                        logger.info(f"成功获取元素文本: {element}")
                        return {"status": "success", "message": "文本获取成功", "data": {"text": element_text}}
                    
                    else:
                        logger.error(f"未知的浏览器操作: {operation}")
                        return {"status": "error", "message": f"未知的浏览器操作: {operation}"}
                except Exception as e:
                    logger.error(f"浏览器操作失败: {str(e)}")
                    return {"status": "error", "message": f"浏览器操作失败: {str(e)}"}
                finally:
                    # 确保浏览器关闭
                    if 'driver' in locals():
                        driver.quit()
            
            elif node_type == "desktop":
                # 桌面操作节点 - 使用pyautogui
                import pyautogui
                import pygetwindow as gw
                
                operation = resolved_params.get("operation", "move")
                x = resolved_params.get("x", 0)
                y = resolved_params.get("y", 0)
                window_title = resolved_params.get("window_title", "")
                
                try:
                    if operation == "move":
                        pyautogui.moveTo(x, y)
                        logger.info(f"移动鼠标到: ({x}, {y})")
                        return {"status": "success", "message": "鼠标移动成功"}
                    
                    elif operation == "click":
                        pyautogui.click(x, y)
                        logger.info(f"点击坐标: ({x}, {y})")
                        return {"status": "success", "message": "点击成功"}
                    
                    elif operation == "double_click":
                        pyautogui.doubleClick(x, y)
                        logger.info(f"双击坐标: ({x}, {y})")
                        return {"status": "success", "message": "双击成功"}
                    
                    elif operation == "type":
                        text = resolved_params.get("text", "")
                        pyautogui.typewrite(text)
                        logger.info(f"输入文本: {text}")
                        return {"status": "success", "message": "文本输入成功"}
                    
                    elif operation == "find_window":
                        windows = gw.getWindowsWithTitle(window_title)
                        if windows:
                            window = windows[0]
                            window.activate()
                            logger.info(f"找到并激活窗口: {window_title}")
                            return {"status": "success", "message": "窗口激活成功", "data": {"window": window.title}}
                        else:
                            logger.warning(f"未找到窗口: {window_title}")
                            return {"status": "warning", "message": f"未找到窗口: {window_title}"}
                    
                    else:
                        logger.error(f"未知的桌面操作: {operation}")
                        return {"status": "error", "message": f"未知的桌面操作: {operation}"}
                except Exception as e:
                    logger.error(f"桌面操作失败: {str(e)}")
                    return {"status": "error", "message": f"桌面操作失败: {str(e)}"}
            
            else:
                logger.error(f"未知的节点类型: {node_type}")
                return {"status": "error", "message": f"未知的节点类型: {node_type}"}